package com.security.config.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.system.entity.SysUser;
import com.security.utils.JwtTokenUtil;
import com.security.utils.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private JwtTokenUtil jwtTokenUtil;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
        super.setFilterProcessesUrl("/jwtLogin");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 从输入流中获取到登录的信息
        try {
            SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
            System.out.println(sysUser);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword())
            );
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails)authResult.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("header",token);
        Map<String,String> map = new HashMap<>();
        map.put(jwtTokenUtil.getHeader(),token);
        response.getWriter().write(JSON.toJSONString(R.success(map)));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        failed.printStackTrace();
        System.out.println(failed.getMessage());
        if (failed instanceof BadCredentialsException){
            System.out.println("BadCredentialsException");
            response.getWriter().write(JSON.toJSONString(R.error(HttpStatus.UNAUTHORIZED.value(),"密码错误")));
        }
        if (failed instanceof InternalAuthenticationServiceException){
            System.out.println("InternalAuthenticationServiceException");
            response.getWriter().write(JSON.toJSONString(R.error(HttpStatus.UNAUTHORIZED.value(),failed.getMessage())));
        }
        if (failed instanceof DisabledException){
            System.out.println("DisabledException");
            response.getWriter().write(JSON.toJSONString(R.error(HttpStatus.UNAUTHORIZED.value(),"用户被禁用")));
        }
    }
}
